package fh.app4stud.mensa;

import android.app.Activity;
import android.content.*;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import fh.app4stud.mensa.data.RestaurantLocation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: iplese
 * Date: 05.04.11
 * Time: 20:21
 * Version 1.0
 * To change this template use File | Settings | File Templates.
 */
public class LocationList extends Activity {

    static final private int MENU_PREFERENCES = Menu.FIRST + 1;
    private static final int SHOW_PREFERENCES = 1;
    private static final String TAG = "This one is my";

    private boolean mensaLocationBound = false;
    private MensaLocationService mensaLocationService;
    Button more;
    ArrayList<RestaurantLocation> locationsList ;
    ListView locationListView;
    ArrayList<String> locations = new ArrayList<String>();
    ArrayAdapter<String> aa;
    //ArrayList<RestaurantLocation> locations = new ArrayList<RestaurantLocation>();

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(fh.app4stud.mensa.R.layout.location_list);

        ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

            //we've bound to local service, cast the Ibinder and get localSErvice instance
            MensaLocationService.LocalBinder binder = (MensaLocationService.LocalBinder) iBinder;
            mensaLocationService = binder.getService();
            mensaLocationBound = true;
        }

        public void onServiceDisconnected(ComponentName componentName) {
            mensaLocationBound = false;
        }
    };


        Intent intent = new Intent(this, MensaLocationService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

        locationListView = (ListView) this.findViewById(fh.app4stud.mensa.R.id.location_list_view);

        int layoutID = android.R.layout.simple_list_item_1;
        //aa = new ArrayAdapter<RestaurantLocation>(this, layoutID, locations);
        aa = new ArrayAdapter<String>(this, layoutID, locations);
        locationListView.setAdapter(aa);

        more = (Button) findViewById(R.id.location_list_button_more);

        locationsList = new ArrayList<RestaurantLocation>();
        locationsList = mensaLocationService.getRestaurantLocations('c');

/*      preferredLocationsNames = new ArrayList<String>();
        for (Iterator i = locationsList.iterator(); i.hasNext();){
            RestaurantLocation item = (RestaurantLocation)i.next();
            preferredLocationsNames.add(item.getLocationName());
        }
        preferredLocationsView = (ListView)this.findViewById(R.id.list_of_preferred_locations);
        int layoutID = android.R.layout.simple_list_item_1;
        preferredLocationsAA = new ArrayAdapter(this, layoutID, preferredLocationsNames);
        preferredLocationsView.setAdapter(preferredLocationsAA);
*/


        hookUpButton();
        refreshLocations();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(0, MENU_PREFERENCES, Menu.NONE, R.string.location__menu_more);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case (MENU_PREFERENCES): {
                Intent i = new Intent(this, LocationListPreferences.class);
                startActivityForResult(i, SHOW_PREFERENCES);
                return true;
            }

        }

        return false;
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService

    }

   /* @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mensaLocationBound) {
            unbindService(mConnection);
            mensaLocationBound = false;
        }
    }
*/
    void refreshLocations() {
        try {

            String myFeed = getString(fh.app4stud.mensa.R.string.my_feed);
            URL url = new URL(myFeed);

            URLConnection connection = url.openConnection();
            Log.i(TAG, "url opend");


            int responseCode = -1;
            HttpURLConnection httpConnection = null;
            int iRetry = 0;

            while (iRetry < 10) {
                iRetry++;
                try {
                    httpConnection = (HttpURLConnection) connection;
                    httpConnection.setConnectTimeout(3000);
                    httpConnection.setDoInput(true);
                    httpConnection.connect();
                    responseCode = httpConnection.getResponseCode();
                } catch (IOException e) {
                    e.printStackTrace();
                    responseCode = -1;
                }
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    iRetry = 10;
                    Log.i(TAG, "If it came to here web service is working");
                    InputStream in = httpConnection.getInputStream();

                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

                    Document dom = documentBuilder.parse(in);
                    Element documentElement = dom.getDocumentElement();

                    //Clear old locations ... deprecated
                    locations.clear();

                    //Get a list of each locations entry.
                    addAllLocations(documentElement);
                } else {
                    iRetry = 10;
                    //TODO create a dialog, ask if they want to chose the saved locations
                    Log.i(TAG, "If it came to here the web service is NOT working");
                    Resources myResources = getResources();
                    InputStream inputStream = myResources.openRawResource(R.raw.locations);
                    Log.i(TAG, "got the locations");
                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                    Document document = documentBuilder.parse(inputStream);
                    Element documentElement = document.getDocumentElement();
                    Log.i(TAG, "almost there");
                    addAllLocations(documentElement);
                    Log.i(TAG, "calling addalllocations");
                }
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } finally {
        }
    }

    private void addAllLocations(Element documentElement) {
            Log.i(TAG, "In addalllocations");
        NodeList nodeList = documentElement.getElementsByTagName("location");

        if (nodeList != null && nodeList.getLength() > 0) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element location = (Element) nodeList.item(i);
                Element city = (Element) location.getElementsByTagName("city").item(0);
                Element houseNumber = (Element) location.getElementsByTagName("houseNumber").item(0);
                Element locationName = (Element) location.getElementsByTagName("locationName").item(0);
                Element street = (Element) location.getElementsByTagName("street").item(0);
                Element zipCode = (Element) location.getElementsByTagName("zipCode").item(0);

                String _city = city.getFirstChild().getNodeValue();
                String _houseNumber = houseNumber.getFirstChild().getNodeValue();
                String _locationName = locationName.getFirstChild().getNodeValue();
                String _streetName = street.getFirstChild().getNodeValue();
                String ZIPCode = zipCode.getFirstChild().getNodeValue();

                RestaurantLocation restaurantLocation = new RestaurantLocation(_city, _houseNumber, _locationName, _streetName, ZIPCode);

                addNewLocation(restaurantLocation);
            }
        }
    }

    private void hookUpButton() {

    }

    private void addNewLocation(RestaurantLocation location) {
        Log.i(TAG, "in add new location");
        String locationDescription = location.getLocationName() + "\n"
                + location.getStreetName() + " " + location.getHouseNumber().toString() + "\n"
                + location.getCity();

        //add location to the location array
        Log.i(TAG, "add to array");
        locations.add(locationDescription);
        //notify  the array adapter
        aa.notifyDataSetChanged();
    }


}

